<template>
  <el-row class="up-row">
    <el-col :span="4" :offset="12" style="font-size: 20px">
      <time>{{ timer }}</time>
    </el-col>
    <el-col :span="1" >
      <el-tooltip content="系统使用说明" placement="top" effect="light">
        <el-icon @click="handleClick" :size="25"><InfoFilled /></el-icon>
      </el-tooltip>
    </el-col>
    <el-col :span="1" >
      <el-tooltip content="电话簿" placement="top" effect="light">
      <el-icon @click="phoneBtn=true" :size="25"><Notebook /></el-icon>
      </el-tooltip>
    </el-col>
    <el-col :span="1">
      <el-tooltip content="我的审批" placement="top" effect="light">
        <el-icon @click="mycheckBtn" :size="25"><Finished /></el-icon>
      </el-tooltip>
    </el-col>
    <el-col :span="1">
      <el-tooltip content="消息" placement="top" effect="light">
        <el-icon @click="bellBen=true" :size="25"><Bell /></el-icon>
      </el-tooltip>
    </el-col>
    <el-col :span="1">
      <el-tooltip content="外聘须知" placement="top" effect="light">
        <el-icon @click="questionBtn=true" :size="25"><QuestionFilled /></el-icon>
      </el-tooltip>
    </el-col>

    <el-col :span="1" >
      <img :src="userInfo.userimg" style="margin-top:25px;width:50px;height:50px; border-radius: 25px"/>
    </el-col>
    <el-col :span="2">
      <!-- 下拉菜单 -->
      <el-dropdown >
              <span class="el-dropdown-link" style="line-height: 100px; color: darkgray; border: 0px;font-size: 20px">
                 <el-icon class="el-icon--left">
                <CaretBottom />
                </el-icon>
                {{userInfo.username}}
              </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :icon="User" @click="rephotoBtn=true">修改头像</el-dropdown-item>
            <el-dropdown-item :icon="Setting" @click="repassBtn=true">修改密码</el-dropdown-item>
            <el-dropdown-item :icon="CircleClose" @click="cancleBtn">退出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-col>
  </el-row>
  <el-dialog
      v-model="repassBtn"
      title="修改密码"
      width="500"
  >
    <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="auto"
    >
      <el-form-item prop="password" label="新密码">
        <el-input
            v-model="loginForm.password"
            placeholder="新密码"
            :prefix-icon="Lock"
            show-password
        />
      </el-form-item>
      <el-form-item prop="password2" label="再次输入">
        <el-input
            v-model="loginForm.password2"
            placeholder="请再次输入"
            :prefix-icon="Lock"
            show-password
        />
      </el-form-item>
      <el-form-item   style="margin-left: 40%">
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button type="primary" @click="cancleFormBtn">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog
      v-model="rephotoBtn"
      title="修改头像"
  >
    <el-upload
        class="avatar-uploader"
        action=""
        :http-request="path"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </el-dialog>
  <el-dialog
      v-model="phoneBtn"
      title="电话簿"
      width="1050"
  >
    <el-form
        ref="phoneRef"
        :model="phoneForm"
        :rules="phoneRules">
        <el-row>
          <el-col :span="6">
            <el-form-item prop="username" label="姓名">
              <el-input v-model="phoneForm.username" style="width: 180px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="job" label="主职务">
              <el-input v-model="phoneForm.job" style="width: 180px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门" prop="department">
              <el-select v-model="phoneForm.department" style="width: 180px">
                <el-option label="全部" value="全部"></el-option>
                <el-option label="管理部" value="管理部"></el-option>
                <el-option label="行政部" value="行政部"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="searchBtn">搜索</el-button>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="updateBtn=true">导入</el-button>
          </el-col>
        </el-row>
    <el-table :data="tableData" ref="tableDataRef" stripe border style="height: 100%;width: 1140px" :header-cell-style="{'text-align':'center'}">
      <el-table-column prop="id" label="编号" width="70"  />
      <el-table-column prop="username" label="姓名" width="100"  />
      <el-table-column prop="job" label="职务" width="100" />
      <el-table-column prop="department" label="部门" width="100" />
      <el-table-column prop="phone" label="手机号" width="130" />
      <el-table-column prop="housenum" label="门牌号" width="80" />
      <el-table-column prop="landline" label="座机" width="130" />
      <el-table-column prop="office" label="办公室" width="100"/>
      <el-table-column prop="email" label="邮箱" width="130"/>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button size="small" type="primary" @click="phoneEditBtn(scope.$index, scope.row)">
            <el-icon><Edit /></el-icon>修改
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    </el-form>
  </el-dialog>
  <el-dialog
      v-model="phoneEditState"
      title="修改个人信息"
      width="500"
  >
    <el-form ref="phoneEditRef"
             :model="phoneEdit"
              :rules="phoneEditRules">
      <el-form-item prop="id" >
        <el-input v-model="phoneEdit.id" type="hidden"></el-input>
      </el-form-item>
      <el-form-item prop="office" label="办公室">
        <el-input v-model="phoneEdit.office" ></el-input>
      </el-form-item>
      <el-form-item prop="housenum" label="门牌号">
        <el-input v-model="phoneEdit.housenum" ></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机号">
        <el-input v-model="phoneEdit.phone" ></el-input>
      </el-form-item>
      <el-form-item prop="landline" label="座机">
        <el-input v-model="phoneEdit.landline" ></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="phoneEdit.email" ></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="sureBtn" >确定</el-button>
  </el-dialog>
  <el-dialog v-model="updateBtn"
             title="导入电话簿"
             width="500">
    <div>
      <el-button @click="downloadBtn" type="primary">下载实例模版</el-button>
    </div>
    <div style="margin-top: 10px">
      <el-upload
          ref="uploadRef"
          action=""
          :limit="1"
          :http-request="download"
      >
        <el-button type="primary"  >上传文件</el-button>

      </el-upload>
    </div>
  </el-dialog>
  <el-dialog v-model="bellBen" title="消息列表" >
    <el-table :data="bellData" ref="bellDataRef" stripe border style="height: 100%;width: 100%" :header-cell-style="{'text-align':'center'}">
      <el-table-column prop="mesname" label="消息类型" width="100" />
      <el-table-column prop="mescontent" label="消息内容" width="500" />
    </el-table>
  </el-dialog>
  <el-dialog v-model="questionBtn" title="外聘须知">
    <el-form ref="questionRef"
             :model="question"
             :rules="questionRules">
      <el-form-item prop="extcontent">
      <el-input
          v-model="question.extcontent"
          style="width: 800px"
          :rows="2"
          type="textarea"
          placeholder="须知正文内容"
      />
      </el-form-item>
      <el-button type="primary" @click="questionsureBtn">确认发布</el-button>
    </el-form>
  </el-dialog>
</template>
<script setup>
import {ref, reactive,onMounted, onUnmounted} from 'vue'
// import { useRouter } from "vue-router";
// const router = useRouter() ;
import router from '@/router';
// 导入外部js文件，并命名为 globaljs
import globaljs from '@/assets/js/global'
import {CaretBottom, Edit,CircleClose, Setting, User,InfoFilled,Notebook,Finished,QuestionFilled,Bell,Plus} from "@element-plus/icons";   // global.js 中 export导出未命名
import request from "@/utils/request";
import {ElMessage} from "element-plus";
const timer = ref(1)
const timerRef = ref()
const userInfo = reactive({
  'username' : 'a' ,
  'userimg' : require('@/assets/imgs/userphoto_default.jpg')
})
// 从SessionStorage取出数据
let user = sessionStorage.getItem('username')
const token = JSON.parse(user).token
const username = JSON.parse(user).sysuser.username
const phoneEditState=ref(false)
const questionRef=ref()
//电话簿按钮
const phoneBtn=ref(false)
const phoneRef=ref()
const phoneEditRef=ref()
const updateBtn=ref(false)
//消息模态框
const bellBen=ref(false)
const questionBtn=ref(false)
//外聘须知
//表单初始化
const question=reactive({
  lastmodifier:username,
  extcontent:''
})
//表单规则
const questionRules=reactive({
  extcontent:[
    { max:100,message: '文本内容不能超过100！！', trigger: 'blur' },
    { required: true, message: '必须填写内容！', trigger: 'blur' },
  ]
})
//外聘须知确认发布按钮
const questionsureBtn = () => {
  request({
    url:'http://localhost:8090/systemprovidor/external/updateexternal',
    method:'PUT',
    data:JSON.stringify(question),
    headers:{'content-type':"application/json;charset:UTF-8"}
  }).then(req=>{
    if (200==req.data.errorCode){
      ElMessage({
        type:'success',
        message:'发布成功！'
      })
      questionBtn.value=false
      questionRef.value.resetFields()
    }else {
      ElMessage({
        type:'error',
        message:'发布失败！'
      })
    }
  })
}
//电话簿导入下载按钮
const downloadBtn = () => {
  window.open('http://localhost:8900/systemprovidor/file/download?filename=电话簿上传模板.xlsx')
}
//电话簿上传文件
const download=(params)=>{
  const downloadfile={
    phonebook:params.file
  }
  request({
    url:'systemprovidor/phonebook/importphonebook',
    method:'POST',
    data:downloadfile,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(req=>{
    if(200==req.data.errorCode){
      ElMessage({
        type:'success',
        message:'上传成功！'
      })
      updateBtn.value=false
    }else {
      ElMessage({
        type:'error',
        message:'上传失败！'
      })
    }
  })
}

//电话簿列表修改确定按钮
const sureBtn = () => {
  phoneEditRef.value.validate((valid,fields)=>{
    if(valid){
      request({
        url:'/systemprovidor/phonebook/isexistphone',
        method:'GET',
        params:phoneEdit
      }).then(req=>{
        if (200==req.data.errorCode){
          ElMessage({
            type: 'error',
            message:'手机号已存在！'
          })
        }else {
          request({
            url:'http://localhost:8090/systemprovidor/phonebook/updatephonebook',
            method:'PUT',
            data:JSON.stringify(phoneEdit),
            headers:{
              'content-type':"application/json;charset:UTF-8",
            }
          }).then(req=>{
            if(200==req.data.errorCode){
              ElMessage({
                type:'success',
                message:'修改成功！'
              })
              //修改成功后关闭对话框
              phoneEditState.value=false
              //清空表单信息
              phoneRef.value.resetFields()
              clearTableData()
              phoneBtn.value=false
            }else {
              ElMessage({
                type:'error',
                message:'修改失败！'
              })
            }
          })
        }
      })
    }
  })
}
const clearTableData = () => {
  tableData.value = [];
};
const phoneEditBtn = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)

  phoneEdit.id=rowData.id
  phoneEdit.office=rowData.office
  phoneEdit.housenum=rowData.housenum
  phoneEdit.phone=rowData.phone
  phoneEdit.landline=rowData.landline
  phoneEdit.email=rowData.email

  phoneEditState.value=true
}
//修改表单初始化数据
const phoneEditData={
  id:'',
  office:'',
  housenum:'',
  phone:'',
  phone2:'',
  landline:'',
  email:''
}
//修改表单绑定数据模型
const phoneEdit = reactive({...phoneEditData})
//表格数据
const tableData=ref([])
const bellData=ref([])
const tableDataRef=ref()
const phoneForm=reactive({
  id:'',
  username:'',
  job:'',
  department:'全部',
  phone:'',
  housenum:'',
  landline:'',
  office:'',
  email:''
})
//表单校验
const phoneRules = reactive({
  department:[
    { required: true, message: '必须填写部门', trigger: 'blur' },
  ]
})
const phoneEditRules=reactive({
  landline:[
    {max:11,min:11,message:'座机填写有误',trigger:'blur'}
  ],
  phone:[
    {max:11,min:11,message:'手机号填写有误',trigger:'blur'}
  ],
  housenum:[
    {max:8,message:'门牌号长度最多8位！',trigger:'blur'}
  ]
})
//电话簿搜索按钮
const searchBtn = () => {
  phoneRef.value.validate((valid,fields)=>{
    if(valid){
      request({
        url:'/systemprovidor/phonebook/getallphonebook',
        method:'GET',
        params: {...phoneForm}
      }).then(req=>{
          tableData.value=req.data.data.records
      })
    }
  })
}
//我的审批按钮
const mycheckBtn = () => {
  router.push('/my/mycheck/check')
}
//获取未读消息
const getbellmessage = () => {
  request({
    url:'/systemprovidor/mymessage/getallmymessage',
    method:'GET'
  }).then(req=>{
    if(200==req.data.errorCode){
      bellData.value=req.data.records
    }
  })
}
// 页面加载后，执行业务逻辑，onMounted中可以访问页面元素
onMounted(()=> {
  // getbellmessage()
  // 从SessionStorage取出数据
  let userstr = sessionStorage.getItem('username')
  if (userstr == null || userstr == undefined || userstr == '') {
    router.push('/')
  } else {
    userInfo.username = JSON.parse(userstr).username
  }
  // 更新 userInfo.username
  //////////////////////////////
  // 获取日期时间
  timerRef.value = setInterval(() => {
    timer.value = globaljs.current()
  }, 1000)
})
// 页面停止加载（页面元素销毁，此函数中不能访问页面元素）
onUnmounted(() => {
  clearInterval(timerRef)
})
//退出按钮
const cancleBtn = () => {
  // alert(user)
  request({
    url: 'http://localhost:8500/sys/user/logout',
    method: 'GET',
    headers: {
      'token': token
    }
  }).then(req => {
    if (200 == req.data.errorCode) {
      sessionStorage.clear()
      router.push("/")
    }
  }).catch(error => {
    console.log(error)
  })
}
// 表单引用
const loginFormRef = ref()
// 表单的数据模型
const loginForm = reactive({
  password : '',
  password2:''
})
// 表单的校验规则
const loginRules = reactive({
  password: [
    { required: true, message: '必须填写密码', trigger: 'blur' },
    /*{ min: 6, message: '账号长度至少6位', trigger: 'blur' },*/
    { pattern : /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/ ,
      message: '密码必须是数字和字母相结合，长度至少6位！',
      trigger: 'blur' },
  ]
})
const repassBtn=ref(false)
//修改密码确认按钮
const submitForm=()=> {
  if (loginForm.password!=loginForm.password2){
    ElMessage({
      type: 'error',
      message: '两次填写密码不一致！'
    })
  }else {
    // 从SessionStorage取出数据
    let userstr = sessionStorage.getItem('username')
    const token = JSON.parse(userstr).token
    const formIDData = {
      id: JSON.parse(userstr).sysuser.id,
      password:loginForm.password
    }
    const formgetID = reactive({...formIDData})
    request({
      url: 'http://localhost:8500/sys/user/updatepassword',
      method: 'put',
      data: formgetID,
      headers: {
        'token': token,
        'content-type':"application/json;charset:UTF-8"
      }
    }).then(req => {
      if (200==req.data.errorCode){
        ElMessage({
          type: 'success',
          message: '修改成功！'
        })
        ElMessage({
          type: 'error',
          message: '密码已修改，请重新登陆！'
        })
        //修改密码后登出
        request({
          url:'http://localhost:8500/sys/user/logout',
          method:'get',
          headers: {
            'token': token
          }
        }).then(req=>{
          if (200 == req.data.errorCode){
            sessionStorage.clear()
            router.push("/")
          }
        })
      }else {
        ElMessage({
          type: 'error',
          message: '修改失败！'
        })
      }
    })
  }
  //清空表单数据
  Object.assign(loginForm)
}
//修改密码取消按钮
const cancleFormBtn=()=>{
  // 清空表单数据
  loginFormRef.value.resetFields()
}
//修改头像
const rephotoBtn=ref(false)
const imageUrl=ref('')

const handleAvatarSuccess=(response,uploadFile)=> {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  if (200 == response.data.errorCode){
    userInfo.userimg =response.data.data
  }
}
const path=(param)=>{
  // 从SessionStorage取出数据
  let userstr = sessionStorage.getItem('username')
  const PhotoIDData = {
    id: JSON.parse(userstr).sysuser.id,
    userphoto:param.file
  }
  request({
    url:'http://localhost:8500/sys/user/rephoto/'+PhotoIDData.id,
    method:'post',
    data:PhotoIDData,
    headers: {
      'Content-Type': 'multipart/form-data',
    }
  }).then(req=>{
    if(200==req.data.errorCode){
      ElMessage({
        type:"success",
        message:'修改成功！'
      })
      userInfo.userimg =req.data.data
      rephotoBtn.value=false
    }else {
      ElMessage({
        type:"error",
        message:'修改失败！'
      })
    }

  })
}
const beforeAvatarUpload= (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('请上传JPG格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}
//系统使用手册下载按钮
const handleClick = () => {
  window.open('http://localhost:8900/systemprovidor/file/download?filename=系统使用说明书.docx')
}

</script>
<style scoped>
.up-row {
  height: 100px;
  line-height: 100px;
  background-color: cornsilk;
  color: darkgray;
  font-weight: bold;
}

/*去掉头像图标，鼠标移上去后的黑色边框*/
:deep(:focus-visible) {
  outline: none;
}
avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.table{
  height: 600px;
}
/* // 设置表格行高度 */
::v-deep .el-table__body tr,
::v-deep .el-table__body td {
  height: 54px;
  text-align: center;
}
</style>